import { createRouter, createWebHistory } from 'vue-router'
import layout from '@/views/layout/LayoutContainer.vue'
import { useUserStore } from '@/stores'
// createRouter 创建路由实例
// 配置 history 模式
// 1. history模式：createWebHistory     地址栏不带 #
// 2. hash模式：   createWebHashHistory 地址栏带 #
// console.log(import.meta.env.DEV)

// 静态路由
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/LoginPage.vue'),
    meta: { hidden: true }
  }, // 登录页
  {
    path: '/',
    component: layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: () => import('@/views/home/index.vue')
      }
    ],
    meta: {
      hidden: false,
      title: '首页'
    }
  }
]

// 动态路由
const asynchrousRoutes = [
  {
    path: '/banner',
    component: layout,
    children: [
      {
        path: '',
        component: () => import('@/views/banner/index.vue')
      }
    ],
    meta: {
      hidden: false,
      title: 'banner管理'
    }
  },
  {
    path: '/user',
    component: layout,
    children: [
      {
        path: '',
        component: () => import('@/views/user/index.vue')
      },
      {
        path: 'details/:id?',
        component: () => import('@/views/user/details.vue')
      }
    ],
    meta: {
      hidden: false,
      title: '用户管理'
    }
  },

  {
    path: '/role',
    component: layout,
    children: [
      {
        path: '',
        component: () => import('@/views/role/index.vue')
      }
    ],
    meta: {
      hidden: false,
      title: '角色管理'
    }
  },
  {
    path: '/permission',
    component: layout,
    children: [
      {
        path: '',
        component: () => import('@/views/permission/index.vue')
      }
    ],
    meta: {
      hidden: false,
      title: '权限管理'
    }
  },
  {
    path: '/audit',
    component: layout,
    children: [
      {
        path: '',
        component: () => import('@/views/audit/index.vue')
      },
      {
        path: 'auditVehicle/:id',
        component: () => import('@/views/audit/auditPage.vue')
      }
    ],
    meta: {
      hidden: false,
      title: '审批管理'
    }
  }
]

// 添加动态路由
const addAsyncRoutes = (asyncRoutes) => {
  asyncRoutes.forEach((e) => router.addRoute(e))
}

// vite 中的环境变量 import.meta.env.BASE_URL  就是 vite.config.js 中的 base 配置项
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: constantRoutes
})

// 重置路由
export function resetRouter() {
  const newRouter = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: constantRoutes
  })
  router.matcher = newRouter.matcher // reset router
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  //1. 用户有token
  if (userStore.token) {
    // 1. 访问登录页则跳转到首页
    if (to.path === '/login') {
      next('/')
    } else {
      // 2. 用户信息不存在则发请求获取
      if (!userStore.userInfo.id) {
        // 发送请求获取用户信息存入pinia
        await userStore.setUserInfo()
        // 3. todo: 根据用户权限添加动态路由
        const permRangeList = await userStore.setPermRange()
        console.log(permRangeList)
        const routes = asynchrousRoutes.filter((route) => {
          // flag为false表示用户有此路由权限
          const flag = permRangeList.every((e) => {
            return e.permCode !== route.path.substring(1)
          })
          return !flag
        })

        //4. 添加动态路由
        await userStore.setRoutes(routes)
        addAsyncRoutes(routes)
        next(to.path)
      } else {
        // 放行
        next()
      }
    }
  } else {
    // 不访问登录页则拦截到登录页，否则放行
    if (to.path !== '/login') {
      // 跳转到登录页
      // eslint-disable-next-line no-undef
      ElMessage({ type: 'error', message: '请先登录' })
      next(`/login?redirect=${to.path}`)
    } else {
      next()
    }
  }
})

export default router
